package cn.tedu.onlinestore.cart.service.impl;

import cn.tedu.onlinestore.cart.mapper.CartMapper;
import cn.tedu.onlinestore.cart.pojo.dto.CartParam;
import cn.tedu.onlinestore.cart.pojo.entity.Cart;
import cn.tedu.onlinestore.cart.pojo.vo.CartVO;
import cn.tedu.onlinestore.cart.service.CartService;
import cn.tedu.onlinestore.product.pojo.vo.ProductVO;
import cn.tedu.onlinestore.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    CartMapper cartMapper;
    @Autowired
    ProductService productService;
    @Override
    public void addCart(CartParam cartParam) {
        log.debug("添加购物车业务：{}",cartParam);
        ProductVO productVO = productService.selectProductById(cartParam.getProductsId());
        Cart cart = new Cart();
        cart.setUserId(cartParam.getUserId());
        cart.setProductsId(cartParam.getProductsId());
        cart.setAmount(cartParam.getAmount());
        double total = Double.parseDouble(productVO.getPrice()) * cartParam.getAmount();
        cart.setTotal(total);
        cart.setCreateTime(new Date());
        cartMapper.insertCart(cart);
    }

    @Override
    public List<CartVO> cartList(Long id) {
        log.debug("查询购物车列表业务：{}",id);
        List<Cart> cartList = cartMapper.cartList(id);
        List<CartVO> cartVOList = new ArrayList<>();
        for (Cart cart : cartList) {
            ProductVO productVO = productService.selectProductById(cart.getProductsId());
            CartVO cartVO = new CartVO();
            BeanUtils.copyProperties(cart,cartVO);
            cartVO.setName(productVO.getName());
            cartVO.setDescription(productVO.getDescription());
            cartVO.setPrice(productVO.getPrice());
            cartVOList.add(cartVO);
        }
        return cartVOList;
    }

    @Override
    public void update(List<CartVO> cartList) {
        log.debug("修改购物车业务：{}",cartList);
        for (CartVO cart : cartList) {
            Cart cart1 = new Cart();
            BeanUtils.copyProperties(cart,cart1);
            cart1.setTotal(cart.getAmount()* Double.parseDouble(cart.getPrice()));
            cartMapper.update(cart1);
        }
    }

    @Override
    public void deleteCart(Long id) {
        log.debug("删除购物车业务：{}",id);
        cartMapper.deleteById(id);
    }

    @Override
    public void deleteByUserId(Long userId) {
        log.debug("通过用户ID删除购物车业务：{}",userId);
        cartMapper.deleteByUserId(userId);
    }

}
